import { Http } from '@/@nasty/Axios';
import { util } from '@/@nasty/Util';
import Upload from '@/@nasty/components/Upload';
import { PlusOutlined } from '@ant-design/icons';
import { ActionType, ModalForm, ProColumns, ProFormInstance, ProFormItem, ProFormSelect, ProFormText, ProFormTextArea, ProTable } from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import { Button, Checkbox, Divider, message } from 'antd';
import React from 'react';
import { FC, cloneElement, useCallback, useRef, useState } from 'react';

async function getPageApi(
    params: any,
    options?: any,
) {
    return new Promise<any>((resolve, reject) => {
        Http.post("/System/Role/GetRolePage", { ...params }, { isLower: true })
            .then((data) => {
                resolve(data);
            }).catch((e) => {
                reject(e)
            })
    });

}


const SelectRoleModel: FC<any> = (props) => {
    const { params, trigger, multiple, defaultValue, onSelect, openReload } = props;
    const [messageApi, contextHolder] = message.useMessage();
    const formRef = useRef<ProFormInstance>();
    const actionRef = useRef<ActionType>();
    const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
    const [selectedRows, setSelectedRows] = useState<any[]>([]);


    const columns: ProColumns<any>[] = [
        {
            title: "角色名称",
            dataIndex: 'Name',
        },
        {
            title: "角色编码",
            dataIndex: 'Code'
        },
        {
            title: "创建时间",
            dataIndex: 'CreateTime',
            hideInSearch: true,
        },
        {
            title: "创建人",
            dataIndex: 'CreateUser',
            hideInSearch: true,
        }
    ];

    const getDefaultValue = () => {
        if (typeof defaultValue === 'function') {
            return defaultValue();
        }
        else {
            return defaultValue;
        }

    }
    return (
        <>
            {contextHolder}
            <ModalForm
                title={"选择角色"}
                trigger={trigger}

                formRef={formRef}
                modalProps={{ okButtonProps: {} }}
                onFinish={async (value) => {
                    if (selectedRowKeys.length === 0) {
                        message.warning('请至少选择一项');
                        return false;
                    }

                    let rows = selectedRows.map((t) => { return { value: t.Id, label: t.Name } });
                    let items = multiple ? rows : rows[0];
                    onSelect(items);
                    return true;
                }}

                onOpenChange={(v) => {
                    if (v) {
                        if (openReload) actionRef.current?.reload();
                        let defs = getDefaultValue() || [];
                        if (!Array.isArray(defs)) defs = [defs];
                        defs = defs.map((t: any) => { return { Id: t.value || t.Id, Name: t.label || t.Name } });
                        let keys = defs.map((t: any) => t.Id);
                        setSelectedRowKeys(keys);
                        setSelectedRows(defs);
                    }
                }}
            >

                <ProTable<any, any>
                    headerTitle={"角色列表"}
                    actionRef={actionRef}
                    rowKey="Id"
                    search={{
                        labelWidth: 'auto',
                        span: 6, // 根据弹窗宽度调整
                        defaultCollapsed: true, // 默认折叠搜索区域
                    }}

                    rowSelection={{
                        type: multiple ? "checkbox" : "radio",
                        selectedRowKeys,
                        onChange: (keys, rows) => {
                            setSelectedRowKeys(keys);
                            setSelectedRows(rows);
                        },
                    }}
                    tableAlertOptionRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
                        <a onClick={onCleanSelected}>取消选择</a>
                    )}

                    request={(p) => { p = { ...params, ...p }; return getPageApi(p, null); }}
                    columns={columns}
                />
            </ModalForm>
        </>
    );
};


export { SelectRoleModel };
